﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace KWT.DRG_DIP.Common
{
    public class HttpClientHelper
    {
        private readonly HttpClient _httpClient;

        #region  初始化
        /// <summary>
        /// 初始化时支持自定义BaseAddress和超时时间‌:ml-citation{ref="2,3" data="citationList"}
        /// </summary>
        /// <param name="baseAddress"></param>
        /// <param name="timeout"></param>
        public HttpClientHelper(string baseAddress, TimeSpan? timeout = null)
        {
            _httpClient = new HttpClient { BaseAddress = new Uri(baseAddress) };
            _httpClient.Timeout = timeout ?? TimeSpan.FromSeconds(30);
        }
        #endregion

        #region 私有方法  统一反序列化逻辑
        /// <summary>
        /// 统一反序列化逻辑
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <returns></returns>
        private async Task<T> DeserializeResponse<T>(HttpResponseMessage response)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<T>(responseContent);
        }
        #endregion

        #region 设置公共请求头（如认证信息）
        /// <summary>
        /// 设置公共请求头（如认证信息）‌:ml-citation{ref="3" data="citationList"}
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void SetDefaultHeaders(string key, string value)
        {
            if (_httpClient.DefaultRequestHeaders.Contains(key))
                _httpClient.DefaultRequestHeaders.Remove(key);
            _httpClient.DefaultRequestHeaders.Add(key, value);
        }
        #endregion

        #region GET请求封装
        /// <summary>
        /// GET请求封装‌
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpoint"> 请求方法 /api/Basic/Role/List </param>
        /// <returns></returns>
        public string Get(string endpoint)
        {
            var response = _httpClient.GetAsync(endpoint).Result;
            response.EnsureSuccessStatusCode();
            ApiResult apiResult = DeserializeResponse<ApiResult>(response).Result;
            if (apiResult.flag)
            {
                return apiResult.data.ToString();
            }
            else
            {
                throw new Exception("执行错误:" + apiResult.msg);
            }
        }

        /// <summary>
        /// 通过扩展方法转换对象为查询字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpoint">请求方法</param>
        /// <param name="parameters">参数 </param>
        /// <returns></returns>
        public string Get(string endpoint, object parameters)
        {
            var query = string.Join("&",
                parameters.GetType().GetProperties()
                    .Select(p => $"{p.Name}={Uri.EscapeDataString(p.GetValue(parameters)?.ToString() ?? "")}"));

            var fullUrl = $"{endpoint}?{query}";
            return Get(fullUrl);
        }
        #endregion

        #region POST请求封装
        /// <summary>
        /// POST请求封装‌:ml-citation{ref="1,2" data="citationList"}
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpoint"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Post(string endpoint, object data)
        {
            var content = new StringContent(
                JsonSerializer.Serialize(data),
                Encoding.UTF8,
                "application/json"
            );
            var response = _httpClient.PostAsync(endpoint, content).Result;
            response.EnsureSuccessStatusCode();

            ApiResult apiResult = DeserializeResponse<ApiResult>(response).Result;
            if (apiResult.flag)
            {
                return apiResult.msg;
            }
            else
            {
                throw new Exception("执行错误:" + apiResult.msg);
            }
        }
        #endregion

        /// <summary>
        /// 测试添加head ，待删除
        /// </summary>
        public void AddHeadTest()
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOiIxIiwiVGVuYW50SUQiOiIxIiwiUm9sZUlEIjoiOTkiLCJuYmYiOjE3NDE2ODY2NjIsImV4cCI6MTc1MzY4NjY2MiwiaWF0IjoxNzQxNjg2NjYyfQ.UNzx24ZkkqPkVkmQHhl7c_BPzPoRPRMpKLZ1z_Q9Ae8";
            SetDefaultHeaders("Authorization", $"Bearer {token}");
            SetDefaultHeaders("TenantID", "1");
        }

    }

    public class ApiResult
    {

        public bool flag { get; set; }
        public string msg { get; set; } = "";
        public int code { get; set; }
        public string trace_id { get; set; } = "";

        public object data { get; set; } = "";
    }
}
